<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title="贷款申请"
    width="600px"
    @opened="onDialogOpened"
    @closed="onDialogClosed"
  >
    <div class="loan-apply-content">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="贷款金额" prop="amount">
          <el-input
            v-model="form.amount"
            placeholder="请输入贷款金额"
            type="number"
            :min="1000"
            ref="amountInputRef"
          >
            <template #append>元</template>
          </el-input>
          <div class="amount-hints">
            <span>最小贷款金额：¥1,000</span>
            <span>最大贷款金额：¥1,000,000</span>
          </div>
        </el-form-item>
        
        <el-form-item label="贷款期限" prop="loanTerm">
          <el-select v-model="form.loanTerm" placeholder="请选择贷款期限" style="width: 100%">
            <el-option label="3个月" :value="3"></el-option>
            <el-option label="6个月" :value="6"></el-option>
            <el-option label="12个月" :value="12"></el-option>
            <el-option label="18个月" :value="18"></el-option>
            <el-option label="24个月" :value="24"></el-option>
            <el-option label="36个月" :value="36"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="还款方式" prop="repaymentMethod">
          <el-select v-model="form.repaymentMethod" placeholder="请选择还款方式" style="width: 100%">
            <el-option label="等额本息" :value="1"></el-option>
            <el-option label="等额本金" :value="2"></el-option>
            <el-option label="一次性还本付息" :value="3"></el-option>
          </el-select>
          <div class="repayment-hint">
            <span v-if="form.repaymentMethod === 1">等额本息：每月还款金额固定</span>
            <span v-else-if="form.repaymentMethod === 2">等额本金：每月还款本金固定，利息递减</span>
            <span v-else-if="form.repaymentMethod === 3">一次性还本付息：到期一次性归还本金和利息</span>
          </div>
        </el-form-item>
        
        <el-form-item label="贷款用途" prop="purpose">
          <el-input
            v-model="form.purpose"
            type="textarea"
            placeholder="请简要说明贷款用途"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="预估信息" v-if="estimatedInfo">
          <div class="estimated-info">
            <div class="info-item">
              <span class="info-label">预估月还款：</span>
              <span class="info-value highlight">¥{{ formatAmount(estimatedInfo.monthlyPayment) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">预估总利息：</span>
              <span class="info-value">¥{{ formatAmount(estimatedInfo.totalInterest) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">预估年利率：</span>
              <span class="info-value">{{ estimatedInfo.annualRate }}%</span>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="支付密码" prop="paymentPassword">
          <el-input
            v-model="form.paymentPassword"
            type="password"
            placeholder="请输入支付密码"
            maxlength="20"
            show-password
            autocomplete="new-password"
          />
        </el-form-item>
      </el-form>
      
      <div class="loan-agreement">
        <el-checkbox v-model="agreeTerms" :disabled="loading">
          我已阅读并同意
          <el-link type="primary" @click="showAgreement">《贷款协议》</el-link>
          和
          <el-link type="primary" @click="showRiskNotice">《风险提示》</el-link>
        </el-checkbox>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmApply" 
          :loading="loading"
          :disabled="!agreeTerms"
        >
          确认申请
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, nextTick, watch } from 'vue';
import { ElMessage } from 'element-plus';

defineProps({
  visible: {
    type: Boolean,
    required: true
  }
});

const emit = defineEmits(['update:visible', 'confirm']);

// 表单数据
const form = reactive({
  amount: '',
  loanTerm: '',
  repaymentMethod: '',
  purpose: '',
  paymentPassword: ''
});

const formRef = ref(null);
const amountInputRef = ref(null);
const loading = ref(false);
const agreeTerms = ref(false);

// 表单验证规则
const rules = {
  amount: [
    { required: true, message: '请输入贷款金额', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入贷款金额'));
        } else if (parseFloat(value) < 1000) {
          callback(new Error('最小贷款金额为¥1,000'));
        } else if (parseFloat(value) > 1000000) {
          callback(new Error('最大贷款金额为¥1,000,000'));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ],
  loanTerm: [
    { required: true, message: '请选择贷款期限', trigger: 'change' }
  ],
  repaymentMethod: [
    { required: true, message: '请选择还款方式', trigger: 'change' }
  ],
  purpose: [
    { required: true, message: '请输入贷款用途', trigger: 'blur' },
    { min: 10, max: 200, message: '贷款用途长度在10到200个字符', trigger: 'blur' }
  ],
  paymentPassword: [
    { required: true, message: '请输入支付密码', trigger: 'blur' },
    { min: 6, max: 20, message: '支付密码长度在6到20个字符', trigger: 'blur' }
  ]
};

// 工具函数
const formatAmount = (amount) => {
  if (amount === undefined || amount === null) return '0.00';
  return parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 预估信息计算
const estimatedInfo = computed(() => {
  if (!form.amount || !form.loanTerm || !form.repaymentMethod) return null;
  
  const amount = parseFloat(form.amount);
  const term = parseInt(form.loanTerm);
  const method = parseInt(form.repaymentMethod);
  
  // 简化的利率计算（实际应该从后端获取）
  const annualRate = 7.2; // 假设年利率7.2%
  const monthlyRate = annualRate / 12 / 100;
  
  let monthlyPayment = 0;
  let totalInterest = 0;
  
  if (method === 1) { // 等额本息
    monthlyPayment = amount * monthlyRate * Math.pow(1 + monthlyRate, term) / (Math.pow(1 + monthlyRate, term) - 1);
    totalInterest = monthlyPayment * term - amount;
  } else if (method === 2) { // 等额本金
    const principalPayment = amount / term;
    const firstInterest = amount * monthlyRate;
    monthlyPayment = principalPayment + firstInterest;
    totalInterest = amount * monthlyRate * (term + 1) / 2;
  } else if (method === 3) { // 一次性还本付息
    totalInterest = amount * annualRate / 100 * term / 12;
    monthlyPayment = 0; // 到期一次性还款
  }
  
  return {
    monthlyPayment,
    totalInterest,
    annualRate
  };
});

// 监听表单变化，重新计算预估信息
watch([() => form.amount, () => form.loanTerm, () => form.repaymentMethod], () => {
  // 触发预估信息重新计算
});

// 弹窗事件处理
const onDialogOpened = () => {
  // 弹窗打开后自动聚焦到金额输入框
  nextTick(() => {
    if (amountInputRef.value) {
      amountInputRef.value.focus();
    }
  });
};

const onDialogClosed = () => {
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.amount = '';
  form.loanTerm = '';
  form.repaymentMethod = '';
  form.purpose = '';
  form.paymentPassword = '';
  agreeTerms.value = false;
  loading.value = false;
};

// 确认申请
const confirmApply = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    if (!agreeTerms.value) {
      ElMessage.warning('请先阅读并同意贷款协议');
      return;
    }
    
    loading.value = true;
    
    const formData = {
      amount: parseFloat(form.amount),
      loanTerm: parseInt(form.loanTerm),
      repaymentMethod: parseInt(form.repaymentMethod),
      purpose: form.purpose,
      paymentPassword: form.paymentPassword
    };
    
    emit('confirm', formData);
    
  } catch (error) {
    console.error('表单验证失败：', error);
  }
};

// 显示协议
const showAgreement = () => {
  ElMessage.info('贷款协议内容...');
};

const showRiskNotice = () => {
  ElMessage.info('风险提示内容...');
};
</script>

<style scoped>
.loan-apply-content {
  padding: 8px;
}

.amount-hints {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.repayment-hint {
  font-size: 12px;
  color: #409eff;
  margin-top: 4px;
}

.estimated-info {
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 12px;
  border: 1px solid #e9ecef;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-label {
  color: #606266;
}

.info-value {
  color: #303133;
  font-weight: 500;
}

.info-value.highlight {
  color: #e6a23c;
  font-weight: 600;
  font-size: 16px;
}

.loan-agreement {
  margin-top: 16px;
  padding: 12px;
  background-color: #fafafa;
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

.dialog-footer {
  text-align: right;
}
</style>
